package encoding_protocol

import (
	"encoding/binary"
	"errors"
	"net"
)

var headerLength = 8

type ConnMsg struct {
}

func (c *ConnMsg) Read(conn net.Conn) ([]byte, error) {
	header := make([]byte, headerLength)
	n, err := conn.Read(header)
	if err != nil {
		return nil, err
	}
	if n != headerLength {
		return nil, errors.New("invalid header length")
	}
	dataLength := binary.BigEndian.Uint64(header)
	data := make([]byte, dataLength)
	n, err = conn.Read(data)
	if err != nil {
		return nil, err
	}
	if n != int(dataLength) {
		return nil, errors.New("invalid Data length")
	}
	return data, nil
}

func (c *ConnMsg) Write(conn net.Conn, data []byte) error {
	val := make([]byte, headerLength+len(data))
	binary.BigEndian.PutUint64(val[:headerLength], uint64(len(data)))
	copy(val[headerLength:], data)
	n, err := conn.Write(val)
	if err != nil {
		return err
	}
	if n != len(data)+headerLength {
		return errors.New("invalid length")
	}
	return nil
}
